package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.common.exception.logicException;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.member.util.AjaxResult;
import cn.wolfcode.luowowo.member.util.AssertUtil;
import cn.wolfcode.luowowo.website.annotion.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {


    @Reference
    private IUserInfoService userInfoService;

    @RequestMapping("/hello")
    @RequireLogin
    @ResponseBody
    public Object hello(Long id){
        return userInfoService.get(id);
    }

    //判断手机号码是否被注册
    @RequestMapping("/checkPhone")
    @ResponseBody
    public Object checkPhone(String phone){
        return !userInfoService.checkPhone(phone);
    }

    //发送验证码
    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public AjaxResult sendVerifyCode(String phone){
        AjaxResult ajaxResult = new AjaxResult();
        userInfoService.sendVerifyCode(phone);
        return ajaxResult;
    }

    //用户注册
    @RequestMapping("/userRegist")
    @ResponseBody
    //dubbo异常处理逻辑（要么实现接口要么在方法签名上声明）
    public AjaxResult userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) throws logicException {
        userInfoService.userRegist(phone, nickname, password, rpassword, verifyCode);
        return AjaxResult.SUCCESS;
    }

    //用户登录
    @RequestMapping("/userLogin")
    @ResponseBody
    public AjaxResult userLogin(HttpServletResponse response, HttpServletRequest request, String username, String password){
        String token = userInfoService.userLogin(username, password);
        //把token放进cookie中，并且设置存活为30分钟
        //CookieUtil.addCookie("token", token, RedisKeys.USER_LOGIN_TOKEN .getTime().intValue(), response);

        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(RedisKeys.USER_LOGIN_TOKEN.getTime().intValue());
        cookie.setPath("/");
        response.addCookie(cookie);
        return AjaxResult.SUCCESS;
    }
}
